const app = getApp()
const util = require('../../../../../../utils/util.js');
const api = require('../../../../../../config/api.js');
Page({
  data: {
    circleid: "",//圈子id
    themeid: "",//主题id
    feeSettingSwitch: 0,//收益开关
    themeAmount: {},//收益明细
    themeAmountDetails: {},//单个收益明细详情
    themeAmountDetailsList: [],//多个收益明细详情
    themeNotice: '',//主题公告
    contentType: "",//主题类型类型
    openTicketList: true,//票种列表开关
    showRefund: false,//是否显示退款面板
    refundTimeArr: [1, 2, 3, 4,5,6,7],//选择退款天数
    refundDay: 1,//选中的的退款天数
  },
  onLoad: function (options) {
    var _this = this;
    var themeid = options.themeid;
    var contentType = options.contentType
    _this.setData({
      contentType: contentType,
      themeid: themeid,
      circleid: options.circleid
    })
    if (themeid != null && String(themeid).length > 0){
      // 需要从数据库获取数据
      _this.getThemeAmountByUpdate();
    } else{
      var feeSettingSwitch = options.feeSettingSwitch == null ? 0 : options.feeSettingSwitch;
      var themeNotice = options.themeNotice == null ? "" : options.themeNotice;
      var themeAmount = JSON.parse(options.themeAmount);
      var themeAmountDetailsList = JSON.parse(options.themeAmountDetailsList);
      var themeAmountDetails = {};
      if (themeAmountDetailsList.length > 0){
        themeAmountDetails = themeAmountDetailsList[0];
      }
      _this.setData({
        feeSettingSwitch: feeSettingSwitch,
        themeNotice: themeNotice,
        themeAmount: themeAmount,
        themeAmountDetails: themeAmountDetails,
        themeAmountDetailsList: themeAmountDetailsList,
      })
      _this.checkTicketList();
    }
  },
  /**
   * 获取付费设置信息
   */
  getThemeAmountByUpdate: function(){
    var _this = this;
    var themeid = _this.data.themeid;
    var circleid = _this.data.circleid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.themeid = themeid;
        data.circleid = circleid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeAmountByUpdateApi, data).then(function (res) {
          if (res.code == 200) {
            var themeAmountDetailsList = res.result.ordThemeAmountDetailsList;
            var themeAmountDetails = {};
            if (themeAmountDetailsList.length > 0) {
              themeAmountDetails = themeAmountDetailsList[0];
            }
            _this.setData({
              themeNotice: res.result.themeNotice,
              feeSettingSwitch: res.result.feeSettingSwitch,
              themeAmount: res.result.ordThemeAmount,
              themeAmountDetailsList: themeAmountDetailsList,
              themeAmountDetails: themeAmountDetails
            })
            _this.checkTicketList();
          }
        })
      })
    }
  },
  onShow: function(){
    var _this = this;
    _this.checkTicketList();
  },
  //输入公告
  inputThemeNotice: function(e){
    var _this = this
    var value = e.detail.value.replace(/\s+/g, '')
    _this.setData({
      themeNotice: value,
    })
  },
  /**
   * 开启、关闭主题收益
   */
  switchChange: function(e){
    var _this = this
    _this.setData({
      feeSettingSwitch: e.detail.value ? 1 : 0,
    })
    if (e.detail.value){
      var designatedType = _this.data.themeAmountDetails.designatedType;
      if (null == designatedType){
        _this.setData({
          ["themeAmountDetails.designatedType"]: 0
        })
      }
    }
    var contentType = _this.data.contentType;
    var themeAmountDetailsList = _this.data.themeAmountDetailsList;
    if (contentType >= 4){
      if (themeAmountDetailsList.length <= 0) {
        _this.addTicket();
      }
      _this.checkTicketList();
    }
  },

  /**
   * 添加一个默认价格标签
   */
  addTicket: function(){
    var _this = this;
    var themeAmountDetails = {};
    themeAmountDetails.name = "默认价格标签名称";
    themeAmountDetails.price = "";
    themeAmountDetails.preferentialSettings = 0;
    themeAmountDetails.preferentialdateStart = "";
    themeAmountDetails.preferentialdateStart = "";
    themeAmountDetails.preferentialdateEnd = "";
    themeAmountDetails.preferentialPrice = "";
    themeAmountDetails.orangeShell = "";
    themeAmountDetails.numberPlaces = "";
    themeAmountDetails.restrictionSetting = "";
    themeAmountDetails.designatedType = 0;
    themeAmountDetails.designatedDays = "";
    themeAmountDetails.commission = "";
    var themeAmountDetailsList = _this.data.themeAmountDetailsList;
    themeAmountDetailsList.push(themeAmountDetails);
    _this.setData({
      themeAmountDetailsList: themeAmountDetailsList
    })
  },
  /**
   * 金额数量
   */
  inputMoney: function(e){
    var _this = this;
    var ordThemeJoinCount = _this.data.themeAmountDetails.ordThemeJoinCount;
    ordThemeJoinCount = ordThemeJoinCount == null || String(ordThemeJoinCount).length <= 0 ? 0 : ordThemeJoinCount;
    if (ordThemeJoinCount > 0){
      util.showToast("已有用户参与了此主题，不能修改金额", "none");
      _this.setData({
        ["themeAmountDetails.price"]: _this.data.themeAmountDetails.price
      })
    }else{
      var price = parseInt(e.detail.value);
      price = price > 0 ? price : "";
      _this.setData({
        ["themeAmountDetails.price"]: price
      })
    }
  },
  /**
   * 选择周期类型
   */
  selecrCycleType: function(e){
    var _this = this;
    var ordThemeJoinCount = _this.data.themeAmountDetails.ordThemeJoinCount;
    ordThemeJoinCount = ordThemeJoinCount == null || String(ordThemeJoinCount).length <= 0 ? 0 : ordThemeJoinCount;
    if (ordThemeJoinCount > 0) {
      util.showToast("已有用户参与了此主题，不能修改周期", "none");
    } else {
      var index = e.currentTarget.dataset.index;
      _this.setData({
        ["themeAmountDetails.designatedType"]: index
      })
    }
  },
  /**
   * 输入指定天数
   */
  inputCycle: function(e){
    var _this = this;
    var ordThemeJoinCount = _this.data.themeAmountDetails.ordThemeJoinCount;
    ordThemeJoinCount = ordThemeJoinCount == null || String(ordThemeJoinCount).length <= 0 ? 0 : ordThemeJoinCount;
    if (ordThemeJoinCount > 0) {
      util.showToast("已有用户参与了此主题，不能修改周期", "none");
      _this.setData({
        ["themeAmountDetails.designatedDays"]: _this.data.themeAmountDetails.designatedDays
      })
    } else {
      var day = parseInt(e.detail.value);
      day = day > 0 ? day : "";
      if (day > 365) {
        util.showToast("不能大于365天", "none");
      } else {
        _this.setData({
          ["themeAmountDetails.designatedDays"]: day
        })
      }
    }
  },
  /**
   * 名额限制
   */
  inputNumberPlaces: function(e){
    var _this = this;
    var restrictionSetting = parseInt(e.detail.value);
    restrictionSetting = restrictionSetting > 0 ? restrictionSetting : "";
    _this.setData({
      ["themeAmountDetails.restrictionSetting"]: restrictionSetting
    })
  },
  //展开关闭票种列表面板
  showTicketList: function(){
    var _this = this
    if (_this.data.openTicketList){
      _this.setData({
        openTicketList: false
      })
    }else{
      _this.setData({
        openTicketList: true
      })
    }
    _this.checkTicketList();
  },
  //打开票种删除面板
  openDelTicket: function(e){
    var _this = this
    var index = e.currentTarget.dataset.index;
    _this.setData({
      selectDelIndex: index,
      showDelTicket: true, 
    })
  },
  //删除票种
  deleteTicket: function(){
    var _this = this
    var index = _this.data.selectDelIndex
    var arr = _this.data.themeAmountDetailsList
    arr.splice(index, 1)
    _this.setData({
      themeAmountDetailsList: arr,
    })
    _this.closeMC();
    _this.checkTicketList();
  },
  //关闭面板
  closeMC: function () {
    var _this = this
    _this.setData({
      showDelTicket: false,
    })
  },
  //是否开启退款设置
  openRefund: function(e){
    var _this = this;
    var refundData = _this.data.themeAmount.refundData;
    if (refundData == null || String(refundData).length <= 0) {
      refundData = 7;
    }
    _this.setData({
      ["themeAmount.refundSettings"]: e.detail.value ? 1 : 0,
      ["themeAmount.refundData"]: refundData,
    })
  },
  //选择退款天数
  selectRefundTime: function(e){
    var _this = this
    var index = e.detail.value;
    var arr = _this.data.refundTimeArr;
    _this.setData({
      ["themeAmount.refundData"]: arr[index]
    })
  },
  //效验是否需要开启退款设置
  checkTicketList: function(){
    var _this = this;
    var feeSettingSwitch = _this.data.feeSettingSwitch;
    if (feeSettingSwitch == 1){
      var count = 0;
      var arr = _this.data.themeAmountDetailsList;
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].price > 0) {
          count += 1
        }
      }
      var refundData = _this.data.themeAmount.refundData;
      if (refundData == null || String(refundData).length <= 0) {
        refundData = 7;
      }
      if (count > 0) {
        _this.setData({
          showRefund: true,
        })
      } else {
        _this.setData({
          showRefund: false,
        })
      }
      if (count > 0 && _this.data.themeAmount.refundSettings == null) {
        _this.setData({
          ["themeAmount.refundSettings"]: 1,
          ["themeAmount.refundData"]: refundData,
        })
      }
    }
  },
  //新增宝贝价格标签
  gotoLabelSetting: function(e){
    var _this = this
    var type = e.currentTarget.dataset.type;
    var themeAmountDetailsList = _this.data.themeAmountDetailsList
    if (type == "add") {
      if (themeAmountDetailsList.length >= 3) {
        util.showToast("不能再添加标签了", "none");
      }else{
        wx.navigateTo({
          url: 'labelSetting/labelSetting?contentType=' + _this.data.contentType + "&index=&themeAmountDetails=" + JSON.stringify("{}"),
        })
      }
    } else {
      // 修改
      var index = e.currentTarget.dataset.index;
      wx.navigateTo({
        url: 'labelSetting/labelSetting?contentType=' + _this.data.contentType + "&index=" + index + "&themeAmountDetails=" + JSON.stringify(themeAmountDetailsList[index]),
      })
    }
  },

  //确定
  submit: function () {
    var _this = this;
    if (!_this.checkInfo()){
      return;
    }
    var themeid = _this.data.themeid;
    var feeSettingSwitch = _this.data.feeSettingSwitch;
    var themeNotice = _this.data.themeNotice;
    var themeAmount = _this.data.themeAmount;
    var themeAmountDetails = _this.data.themeAmountDetails;
    var themeAmountDetailsList = _this.data.themeAmountDetailsList;
    var contentType = _this.data.contentType;
    if (contentType < 4) {
      themeAmountDetailsList.push(themeAmountDetails);
    }
    if(themeid != null && String(themeid).length > 0){
      // 保存数据库
      _this.updateThemeAmount();
    }else{
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2];  //上一个页面
      prevPage.setData({
        ["ordTheme.themeNotice"]: themeNotice,
        ["ordTheme.feeSettingSwitch"]: feeSettingSwitch,
        ["themeAmount"]: themeAmount,
        ["themeAmountDetailsList"]: themeAmountDetailsList, 
      });
      wx.navigateBack({
        delta: 1
      })
    }
  },
  
  /**
   * 修改主题
   */
  updateThemeAmount: function(){
    var _this = this;
    var themeid = _this.data.themeid;
    var feeSettingSwitch = _this.data.feeSettingSwitch;
    var themeNotice = _this.data.themeNotice;
    var themeAmountDetailsList = _this.data.themeAmountDetailsList;
    var themeAmount = _this.data.themeAmount;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.themeid = themeid;
        data.themeNotice = themeNotice;
        data.feeSettingSwitch = feeSettingSwitch;
        data.ordThemeAmount = themeAmount;
        data.ordThemeAmountDetailsList = themeAmountDetailsList;
        data.access_token = res.access_token;
        util.post(api.Interest_UpdateThemeAmountApi, data).then(function (res) {
          if (res.code == 200) {
            wx.navigateBack({
              delta: 1
            })
          }else{
            util.showToast(res.message, "none");
          }
        })
      })
    }
  },

  /**
   * 校验信息
   */
  checkInfo: function () {
    var _this = this;
    var feeSettingSwitch = _this.data.feeSettingSwitch;
    var refundSettings = _this.data.themeAmount.refundSettings;
    if (feeSettingSwitch == 1){
      var contentType = _this.data.contentType;
      if (contentType < 4){
        var themeAmountDetails = _this.data.themeAmountDetails;
        if (themeAmountDetails.price == null || String(themeAmountDetails.price).length <= 0 || parseInt(themeAmountDetails.price) <= 0){
          util.showToast("请输入金额", "none");
          return false;
        }
        if (themeAmountDetails.designatedType == 2){
          if (themeAmountDetails.designatedDays == null || String(themeAmountDetails.designatedDays).length <= 0 || parseInt(themeAmountDetails.designatedDays) <= 0) {
            util.showToast("请输指定天数", "none");
            return false;
          }
        }
      }
    }
    if (refundSettings != 1){
      _this.setData({
        ["themeAmount.refundData"]: 0
      })
    }
    return true;
  }
})